<template>
  <div class="appClass clearfix">
    <div class="text-name"><strong>边缘日记</strong></div>
    <div class="appContainer clearfix">
      <TodoMyHeader @addTodo="addTodo"></TodoMyHeader>
      <TodoInfoList :todos="todos"></TodoInfoList>
      <TodoInfoFoot
        :todos="todos"
        :checkAllTodo="checkAllTodo"
        :clearAllTodo="clearAllTodo"
      ></TodoInfoFoot>
    </div>
  </div>
</template>

<script>
import TodoMyHeader from "./components/TodoMyHeader.vue";
import TodoInfoList from "./components/TodoInfoList.vue";
import TodoInfoFoot from "./components/TodoInfoFoot.vue";
export default {
  name: "App",
  data() {
    return {
      todos: JSON.parse(localStorage.getItem("todo")) || [],
    };
  },
  methods: {
    //添加obj
    addTodo(Obj) {
      this.todos.unshift(Obj);
    },
    //勾选
    checkTodo(id) {
      this.todos.forEach((todoObj) => {
        if (todoObj.id === id) todoObj.done = !todoObj.done;
      });
    },
    //编辑todo
    updataTodo(id, title) {
      this.todos.forEach((todoObj) => {
        if (todoObj.id === id) todoObj.title = title;
      });
    },
    //删除obj
    deleteTodo(id) {
      this.todos = this.todos.filter((todoObj) => {
        return todoObj.id !== id; //过滤出除了我按的这个id之外的所有
      });
    },
    //全选或者全不选
    checkAllTodo(done) {
      this.todos.forEach((todoObj) => {
        todoObj.done = done;
      });
    },
    //删除已完成
    clearAllTodo() {
      this.todos = this.todos.filter((todoObj) => {
        return todoObj.done != true;
      });
    },
  },
  watch: {
    todos: {
      deep: true,
      handler(value) {
        localStorage.setItem("todo", JSON.stringify(value));
      },
    },
  },
  components: {
    TodoInfoList,
    TodoInfoFoot,
    TodoMyHeader,
  },
  mounted() {
    this.$bus.$on("checkTodo", this.checkTodo),
      this.$bus.$on("updataTodo", this.updataTodo),
      this.$bus.$on("deleteTodo", this.deleteTodo);
  },
  //解绑
  beforeDestroy() {
    this.$bus.$off("checkTodo");
    this.$bus.$off("updataTodo");
    this.$bus.$off("deleteTodo");
  },
};
</script>

<style>
.text-name {
  font-size: 18px;
  width: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgb(87, 84, 84);
  position: absolute;
}
.clearfix::after {
  clear: both;
  height: 0;
  content: "";
}
.appClass {
  width: 650px;
  border: 1px solid black;
  margin: 0 auto;
  position: relative;
  display: flex;
  justify-content: center;
  background-color: #f1f1f1;
}
.appContainer {
  width: 550px;
  border: 1px solid black;
  margin: auto auto;
  margin-top: 25px;
  margin-bottom: 25px;
}
</style>
